<?php

namespace app\result\admin;

use app\model\admin\Features;
use app\result\auto\ProjectResult;
use app\result\BaseResult;

class FeaturesResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Features();
    }

    //列表页面配置
    public function list_config()
    {
         return $this->success_return('success', [
            'form_fields' => method_exists($this, 'form_fields') ? $this->form_fields() : [],
            'el_table_column' => $this->el_table_column(),
            'search_fields' => $this->_searchField()
        ]);
    }

    // 表格列
    public function el_table_column(): array
    {
        return [
            ['prop' => 'id', 'type' => 'text', 'label' => '#', 'minWidth' => '100', 'align' => 'center',],
            ['prop' => 'title', 'type' => 'text', 'label' => '功能标题', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'project_name', 'type' => 'text', 'label' => '关联项目', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'status', 'type' => 'text', 'label' => '状态', 'minWidth' => '120', 'align' => 'center',
                'tags' => [
                    ['type' => 'info', 'label' => '未开始', 'value' => '未开始'],
                    ['type' => 'warning', 'label' => '处理中', 'value' => '处理中'],
                    ['type' => 'success', 'label' => '已处理', 'value' => '已处理'],
                    ['type' => 'primary', 'label' => '开发中', 'value' => '开发中'],
                    ['type' => 'success', 'label' => '测试中', 'value' => '测试中'],
                    ['type' => 'warning', 'label' => '等待上线', 'value' => '等待上线'],
                    ['type' => 'success', 'label' => '已上线', 'value' => '已上线'],
                    ['type' => 'info', 'label' => '已作废', 'value' => '已作废']
                ]],
            ['prop' => 'owner', 'type' => 'text', 'label' => '需求方/负责人', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'dev_person', 'type' => 'text', 'label' => '开发人', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'test_person', 'type' => 'text', 'label' => '测试人员', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'description', 'type' => 'text', 'label' => '功能描述', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'images', 'type' => 'image', 'label' => '附件', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'plan_online_time', 'type' => 'text', 'label' => '预计上线时间', 'minWidth' => '180', 'align' => 'left',],
            ['prop' => 'real_online_time', 'type' => 'text', 'label' => '实际上线时间', 'minWidth' => '180', 'align' => 'left',],
            ['prop' => 'created_at', 'type' => 'text', 'label' => '添加时间', 'minWidth' => '180', 'align' => 'left',],
        ];
    }

    //列表搜索字段
    private function _searchField(): array
    {
        return [
            ['name' => 'title', 'label' => '功能名称', 'type' => 'input', 'placeholder' => '功能名称',],
            ['name' => 'owner', 'label' => '负责人', 'type' => 'input', 'placeholder' => '负责人',],
            ['name' => 'status', 'label' => '状态', 'type' => 'select', 'placeholder' => '请选择状态',
                'options' => [
                    //['未开始','处理中','开发中', '测试中', '等待上线', '已上线', '已作废']
                    ['value' => '未开始', 'label' => '未开始'],
                    ['value' => '处理中', 'label' => '处理中'],
                    ['value' => '已处理', 'label' => '已处理'],
                    ['value' => '开发中', 'label' => '开发中'],
                    ['value' => '测试中', 'label' => '测试中'],
                    ['value' => '等待上线', 'label' => '等待上线'],
                    ['value' => '已上线', 'label' => '已上线'],
                    ['value' => '已作废', 'label' => '已作废'],
                ],],
            ['name' => 'project_id', 'label' => '关联项目', 'type' => 'select', 'placeholder' => '选择关联项目',
                'options' => (new ProjectResult)->list_options([], true)

            ],
        ];
    }

    // 获取公共条件限制
    private function _where($args = []): array
    {
        $where = [
            ['deleted_at', '=', 0]
        ];
        if (!empty($args['status'])) {
            $where[] = ['status', '=', $args['status']];
        }
        if (!empty($args['owner'])) {
            $where[] = ['owner', '=', $args['owner']];
        }
        if (!empty($args['project_id'])) {
            $where[] = ['project_id', '=', $args['project_id']];
        }
        if (!empty($args['title'])) {
            $where[] = ['title', 'like', '%' . $args['title'] . '%'];
        }
        return $where;
    }

    public function list($args = []): array
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $sort_by = trim($args['sort_by'] ?? 'id desc');
        $where = $this->_where($args);
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', $sort_by, $page, $pageSize);
        if ($data) {
            $allProject = (new ProjectResult)->list_options([], true);
            if ($allProject) {
                $allProject = array_column($allProject, null, 'value');
            }
            foreach ($data as &$item) {
                $item['images'] = !empty($item['images']) ? array_filter(explode(',', $item['images'])) : [];
                $item['content'] = $item['content'] ? htmlspecialchars_decode(htmlspecialchars_decode($item['content'])) : '';
                $item['project_name'] = !empty($allProject[$item['project_id']]) ? $allProject[$item['project_id']]['label'] : '';
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data,
        ]);
    }

    public function get($args = []): array
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(["id" => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        return $this->success_return('success', [
            'info' => $data
        ]);
    }


    public function set_status($args): array
    {
        $id = intval($args['id'] ?? 0);
        $status = $args['status'];
        if (!$id) {
            return $this->error_return('参数错误');
        }
        if (!$status) {
            return $this->error_return('参数错误');
        }
        $data = $this->model->data_get(["id" => $id], 'status');
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $res = (new Features())->data_update(["id" => $id], ['status' => $status]);
        if (!$res) {
            return $this->error_return('修改状态失败');
        }
        admin_log('修改功能需求状态', $args);
        return $this->success_return('保存成功');
    }

    public function del_data($args): array
    {
        $id = $args['id'] ?? [];
        if (!$id) {
            return $this->error_return('请选择数据');
        }
        $data = $this->model->data_get(['id' => $id], '*')?->toArray();
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $res = $this->model->data_update(['id' => $id], ['deleted_at' => time()]);
        admin_log('删除功能需求', $data);
        return $this->success_return('删除成功');
    }

    public function list_options($args = []): array
    {
        $all = $this->model->data_list_nopage([], 'id,title');
        if ($all) {
            foreach ($all as &$item) {
                $item['label'] = $item['title'];
                $item['value'] = $item['id'];
            }
        }
        return self::success_return('success', [
            'list' => $all,
        ]);
    }


    public function save_data($args): array
    {
        $id = intval($args['id'] ?? 0);

        $rules = [
            ['title', 'empty|max_length:200|min_length:2', '名称不能为空|名称长度在2-200位之间|名称长度在2-200位之间'],
            ['status', 'empty', '请选择状态'],
        ];
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }

        if ($id) {
            $data = $this->model->data_get(['id' => $id]);
            if (!$data) {
                return self::error_return('数据不存在');
            }
        }
        $baseData = [
            'title' => $args['title'],
            'status' => $args['status'],
            'owner' => $args['owner'] ?? '',
            'plan_online_time' => $args['plan_online_time'] ?: null,
            'real_online_time' => $args['real_online_time'] ?: null,
            'dev_person' => $args['dev_person'] ?: '',
            'test_person' => $args['test_person'] ?: '',
            'description' => $args['description'] ?: '',
            'images' => !empty($args['images']) ? join(',', $args['images']) : '',
            'content' => $args['content'] ?: '',
            'project_id' => intval($args['project_id']??0),
        ];
        if ($id) {
            $this->model->data_update(['id' => $id], $baseData);
        } else {
            $this->model->data_add($baseData);
        }
        return $this->success_return('保存成功');
    }


}
